<template>
  <view class="container">
    <scroll-view class="scroll-container" @scroll="handleScroll" scroll-y="true" show-scrollbar="false">
      <view class="cus-header" :style="{'opacity':dynamicOpacity}">
        <view class="btns">
          <view class="btn-items" @click="handleChangeChargeType(1)">
            <image src="http://wx.xiongmaovip.com/miniapp/static/header/fuel.png"></image>
            <p>去加油</p>
          </view>
          <view class="line"></view>
          <view class="btn-items" @click="handleChangeChargeType(2)">
            <image src="http://wx.xiongmaovip.com/miniapp/static/header/charge.png"></image>
            <p>去充电</p>
          </view>
        </view>
      </view>
      <view class="bg-img">
<!--        <image class="bg-image" src="../../static/index/bg_new.png"></image>-->
        <image class="bg-image" src="http://wx.xiongmaovip.com/miniapp/static/index/bg_new.png"></image>
        <view class="search-container">
          <uni-icons class="search-icon" type="search" size="20" color="#CECECE"></uni-icons>
          <input class="search-input" v-model="searchValue" confirm-type="search" placeholder="请输入加油站名称" @confirm="getList()"/>
        </view>
        <view class="cards-panel">
          <view class="card-item" v-for="card in cardItem" @click="handleChangeChargeType(card.id)">
            <image class="card-img" :src="FUELORCHARGE === card.id ? card.chosedPath : card.path"></image>
          </view>
        </view>
      </view>
      <view class="filterPanel">
        <view v-for="item in filterArr" class="filterItem" :class="{'actived': item.id === activeFilter }"
              @click="handleClickFilter(item.id)">{{ item.name }}
        </view>
      </view>
      <view class="listPanel">
        <view class="listCard" v-for="(item,index) in stationDataList" @click="handleClickStation(item)">
          <view class="titlePanel">
            <view>
              <uni-icons type="star" size="18" color="#C2A661"></uni-icons>
              <span class="title">{{item.stationName}}</span>
            </view>
            <view class="locationPanel">
              <uni-icons type="paperplane-filled" size="16" color="#006241"></uni-icons>
              {{item.distance}}km
            </view>
          </view>
          <view class="address">
            <uni-icons type="location" size="16" color="#6A6A6A"></uni-icons>
            {{item.address}}
          </view>
          <view class="cardBottom">
            <view class="status" v-if="FUELORCHARGE === 2">
              <view class="empty">闲</view>
              <view class="num">{{item.freeNozCnt}}/{{item.nozCnt}}</view>
            </view>
            <view class="status" v-else>
              <view class="num">加油合作油站</view>
            </view>

            <view class="price">
              <view>{{FUELORCHARGE === 1 ? '优惠价' : '会员价'}}：
                <span class="vipPirce">￥
                  <b class="num" v-if="FUELORCHARGE === 1">{{nozList[index].price}}</b>
                  <b class="num" v-else>{{(Number(item.periodPrice.eleFeeVip) + Number(item.periodPrice.serFeeVip)).toFixed(2)}}</b>
                  /{{FUELORCHARGE === 1 ? 'L' : '度'}}
                </span>
              </view>
              <view v-if="FUELORCHARGE === 2">
                非会员价：{{(Number(item.periodPrice.eleFee) + Number(item.periodPrice.serFee)).toFixed(2)}}/度
              </view>
            </view>
          </view>
        </view>
      </view>
      <custom-tabbar :curr-page="0" :currentType="FUELORCHARGE"/>
      <!-- #ifdef MP-WEIXIN -->
      <privacyPopup ref="privacyPopup" :code="param.code" :session_key="session_key"></privacyPopup>
      <!-- #endif -->
    </scroll-view>
    <poster class="posterCmp" ref="posterPopup"></poster>
  </view>
</template>

<script>
import customTabbar from '@/components/custom-tabbar.vue'
import configs from '@/config/index'
import poster from '@/components/poster.vue'

import {
  createMemberInfo, getListFuelStation, getListStation,
  getOpenId,
  register,
} from '@/api'
import {
  toast,
  showConfirm,
  tansParams
} from '@/utils/common'
import privacyPopup from '../../components/privacy-popup.vue';
import location from "@/utils/getLocation";


export default {
  components: {
    customTabbar,
    privacyPopup,
    poster
  },
  data() {
    return {
      param: {
        phone_code: '',
        phone_encryptedData: '',
        phone_iv: '',
        code: '',
        access_token: ''
      },
      openId: '',
      session_key: '',
      userInfo: {},
      FUELORCHARGE: 1,
      i: 5,
      cardItem: [
        {id: 1, name: '加油', path: 'http://wx.xiongmaovip.com/miniapp/static/index/fuel-card.png', chosedPath: 'http://wx.xiongmaovip.com/miniapp/static/index/fuel-card-chosed.png'},
        {id: 2, name: '充电', path: 'http://wx.xiongmaovip.com/miniapp/static/index/charge-card.png', chosedPath: 'http://wx.xiongmaovip.com/miniapp/static/index/charge-card-chosed.png'},
      ],
      activeFilter: '',
      filterArr: [
        {id: '', name: '全部'},
        {id: 1, name: '距离优先'},
        // {id: 2, name: '价格优先'},
        // {id: 3, name: '收藏优先'},
      ],
      dynamicOpacity: 0,
      stationDataList: [],
      nozList: [],
      lng: '',
      lat: '',
      searchValue: '',
    }
  },
  onShow() {
    const self = this
    let FUELORCHARGE = uni.getStorageSync('FUELORCHARGE') || 1
    self.FUELORCHARGE = FUELORCHARGE
    if (!FUELORCHARGE || JSON.stringify(this.userInfo) != '{}') {
      uni.login({
        provider: 'weixin', // 使用微信登录
        success: function (loginRes) {
          self.param.code = loginRes.code
          self.getOpenIdFn()
        }
      })
      return
    }
    uni.login({
      provider: 'weixin', // 使用微信登录
      success: function (loginRes) {
        self.param.code = loginRes.code
        self.getOpenIdFn()
      }
    })
    // this.getListFuelStationFn();
  },
  onHide() {
  },
  onLoad(option) {
    this.FUELORCHARGE = uni.getStorageSync('FUELORCHARGE') || 1
    this.getLocation();
    uni.setStorageSync('INDEX', 1)
    if (JSON.stringify(option) !== '{}') {
      this.userInfo = JSON.parse(option.userInfo)
      return
    }
    this.$refs.privacyPopup.getPrivacySet();
  },
  methods: {
    login(){
      uni.login({
        provider: 'weixin', // 使用微信登录
        success: function (loginRes) {
          this.param.code = loginRes.code
          this.getOpenIdFn()
        }
      })
    },
    getLocation() {
      // const _self = this;
      location().then(res => {
        this.lng = res.longitude
        this.lat = res.latitude
        // _self.getListFuelStationFn();
        this.getList()
      }).catch(err => {
        if (!err) {
          this.getList();
        }
      })
    },
    //注册会员
    registerMember(userInfo) {
      register({
        memberName: userInfo.nickName,
        openid: this.openId,
        headImgUrl: userInfo.avatarUrl,
        phoneNum: userInfo.phoneNum
      }).then(data => {
        if (data && data.regActivityCnt == 1) {
          this.getMember('register')
        } else {
          this.getMember()
        }
      }).catch(err => {
        toast('会员注册失败')
      })
    },
    getOpenIdFn() {
      getOpenId({
        code: this.param.code,
      }).then(res => {
        if (res) {
          this.openId = res.openid //openid 用户唯一标识
          this.session_key = res.sessionKey
          uni.setStorageSync('userOpenId', this.openId)
          uni.setStorageSync('userToken', res.sessionKey + res.openid)
          let showPrivacy = uni.getStorageSync('showPrivacy')
          if (this.userInfo.nickName) {
            this.getMember()
          }
          if (showPrivacy == 0 && !this.userInfo.nickName) this.getMember()
        }
      }).catch(error => {
        // uni.hideLoading()
        if (error != 200) {
          toast('请求失败,请重试')
          return
        }
      })
    },
    // 获取会员信息
    getMember(data) {
      createMemberInfo({
        openId: this.openId,
      }).then(res => {
        let showPrivacy = uni.getStorageSync('showPrivacy')
        if (res.wxUser != null) {
          if (data === 'register') {
            // this.$refs.posterPopup.toggle('center')
            this.i = 0
          }
          // if (JSON.stringify(this.userInfo) != '{}') uni.hideLoading()
          uni.setStorageSync('memberInfo', JSON.stringify(res))
          this.userInfo = {}
          return
        }
        if (res.wxUser == null && JSON.stringify(this.userInfo) == '{}') {
          uni.removeStorageSync('memberInfo')
          uni.removeStorageSync('FUELORCHARGE')
          uni.redirectTo({
            url: '/pages/login/index'
          })
          return
        }
        if (JSON.stringify(this.userInfo) != '{}') {
          if (this.i > 0) {
            this.registerMember(this.userInfo)
            this.i--
            console.log('继续注册');
          }
        }
      }).catch(error => {
        uni.removeStorageSync('memberInfo')
        if (error != 200) {
          toast('请求失败,请重试')
        }
      })
    },
    // 去加油
    fuel(e) {
      uni.switchTab({
        url: '/pages/panda-fuel/index'
      })
    },
    // 去充值
    charge() {
      uni.switchTab({
        url: '/pages/panda-charge/index'
      })
    },
    handleClickFilter(id) {
      this.activeFilter = id
      this.getList();
    },
    handleScroll(e) {
      const distanceFromTop = e.detail.scrollTop
      this.dynamicOpacity = Math.min(distanceFromTop / 180, 1);
    },

    handleChangeChargeType(type){
      this.FUELORCHARGE = type
      this.activeFilter = ''
      uni.setStorageSync('FUELORCHARGE', this.FUELORCHARGE)
      this.getList()
    },

    checkAdult(data) {
      return data.prName == '92#';
    },

    getList(){
      this.stationDataList = []
      if (this.FUELORCHARGE === 1){
        this.getListFuelStationFn()
      }else {
        this.getStationListFn()
      }
    },

    // 获取充电站点列表
    getStationListFn() {
      getListStation({
        queryType: this.activeFilter,
        stationType: 2, // 1-加油 2-充电
        lng: this.lng || 103.839971,
        lat: this.lat || 30.686594,
        distance: 9999,
        stationName: this.searchValue || '',
      }).then(res => {
        if (res && res.length) {
          this.stationDataList = res
        } else {
          console.log(res, 'error')
        }
      }).catch(error => {
        // if (error == 'token已过期.') {
        // 	this.getCodeData()
        // }
      })
    },

    // 获取站点列表
    getListFuelStationFn() {
      getListFuelStation({
        queryType: this.activeFilter,
        lng: this.lng || 104.04311,
        lat: this.lat || 30.64242,
        distance: 9999,
        stationName: this.searchValue || '',
      }).then(res => {
        if (res && res.length) {
          this.stationDataList = res
          this.stationDataList.forEach(item => {
            if (item.nozList.length > 0) {
              let res = item.nozList.find(this.checkAdult)
              this.nozList.push(res)
            }
          })
        } else {
          console.log(res, 'error')
        }
      }).catch(error => {
        if (error == 'token已过期.'|| error=='token找不到了.') {
          // this.getCodeData()
        }
      })
    },

    handleClickStation(data){
      if (this.FUELORCHARGE === 1){
        uni.navigateTo({
          url: '/pages/panda-fuel/check-order/index?stationId=' + data.stationId + '&lat=' + this.lat + '&lng=' + this.lng
        })
      }else{
        uni.navigateTo({
          url: '/pages/panda-charge/charge-station-info/index?stationId=' + data.stationId + '&lng=' + this.lng + '&lat=' + this.lat
        })
      }
    }
  },
}
</script>

<style lang="scss" scoped>
view {
  box-sizing: border-box;
}

.container {
  position: relative;
  //padding: 196rpx 24rpx 0rpx;
  font-size: 14px;
  line-height: 24px;
  overflow: scroll;
  height: calc(100vh - 140rpx);

  //.posterCmp{
  //  width: 100%;
  //  height: 100%;
  //  position: fixed;
  //  top: 0;
  //  left: 0;
  //}

  .scroll-container{
    height: calc(100vh - 140rpx);
  }

  .cus-header {
    background: #183E31;
    width: 100%;
    height: 264upx;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 8;
    padding: 88upx 24upx;

    .btns {
      display: flex;
      align-items: center;

      .btn-items {
        color: #FFFFFF;
        font-size: 24upx;
        text-align: center;
        line-height: 36upx;

        image {
          width: 40upx;
          height: 40upx;
        }
      }

      .line {
        width: 2upx;
        height: 32upx;
        background: #F0F1F2;
        margin: 0 24upx;
        opacity: .3;
      }
    }
  }

  .bg-img {
    width: 100%;
    height: 520upx;
    background-size: cover;
    padding: 196upx 24upx 0;
    position: relative;

    .bg-image {
      z-index: -1;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 520upx;
    }

    .search-container {
      position: fixed;
      width: 94%;
      height: 64upx;
      background: #FFFFFF;
      color: #FFFFFF;
      border-radius: 32upx;
      padding: 0 64upx;
      top: 188upx;
      left: 50%;
      transform: translateX(-50%);
      z-index: 9;

      .search-icon {
        position: absolute;
        left: 24upx;
        height: 64upx;
        display: flex;
        align-items: center;
      }

      .search-input {
        line-height: 64upx;
        font-size: 28upx;
        color: #393939;
        width: 100%;
        height: 100%;
      }
    }

    .cards-panel {
      display: flex;
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateY(48upx) translateX(-50%);
      justify-content: space-between;

      .card-item {
        width: 366upx;
        height: 232upx;

        .card-img {
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  .filterPanel {
    width: 100%;
    height: 56upx;
    padding: 0 24upx;
    display: flex;
    margin-top: 56upx;
    justify-content: flex-start;

    .filterItem {
      width: 158upx;
      height: 100%;
      line-height: 56upx;
      border-radius: 32upx;
      background: #FFFFFF;
      color: #6A6A6A;
      text-align: center;
      font-size: 24upx;
      margin-right: 24upx;

      &.actived {
        background: rgba(207, 234, 227, 0.3);
        color: #006241;
      }
    }
  }

  .listPanel {
    padding: 8upx 24upx 56upx;

    .listCard {
      position: relative;
      padding: 32upx 24upx;
      background: #FFFFFF;
      border-radius: 24upx;
      margin-top: 20upx;

      .titlePanel {
        display: flex;
        justify-content: space-between;
        align-content: flex-start;

        .title {
          margin-left: 8upx;
          font-size: 32upx;
          color: #1B1B1B;
          font-weight: 700;
        }

        .locationPanel {
          background: #CFEAE380;
          color: #006241;
          padding: 0 16upx;
          border-radius: 8upx;
          display: flex;
          align-content: center;
          height: 44upx;
          line-height: 44upx;
          font-size: 24upx;
        }
      }

      .address {
        color: #6A6A6A;
        font-size: 24upx;
        font-weight: 400;
        margin-top: 8upx;
      }

      .cardBottom {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;

        .status {
          height: 100%;
          text-align: center;
          display: flex;
          justify-content: start;
          background: #FFF8EA;
          border-radius: 8upx;
          color: #C99227;
          line-height: 40upx;
          font-size: 24upx;
          overflow: hidden;

          .empty {
            text-align: center;
            width: 40upx;
            color: #FFFFFF;
            background: #C99227;
          }

          .num {
            min-width: 100upx;
            padding: 0 16upx;
            text-align: center;
          }
        }

        .vipPirce {
          color: #F57546;

          .num {
            font-weight: 600;
            display: inline-block;
            font-size: 56upx;
          }
        }

        .price {
          font-size: 24upx;
          color: #6A6A6A;
        }
      }
    }
  }

  .bg_box {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    pointer-events: none;

    image {
      width: 100%;
      // height: auto;
    }
  }

  .top {
    font-size: 34rpx;
    font-weight: 500;
    color: #2d2b2a;
    line-height: 48rpx;
    text-align: center;
  }

  .check-btn {
    // display: flex;
    margin-top: 80rpx;

    .fuel {
      width: 590rpx;
      height: 240rpx;
      margin-bottom: 80rpx;
      position: relative;

      .fuel-name {
        position: absolute;
        top: 68rpx;
        right: 80rpx;

        .name {
          font-size: 40rpx;
          font-weight: 500;
          color: #2d2b2a;
          line-height: 56rpx;
        }

        .brief-introduction {
          font-size: 28rpx;
          color: #666260;
          line-height: 40rpx;
        }
      }
    }

    .charge {
      width: 590rpx;
      height: 240rpx;
      position: relative;

      .charge-name {
        position: absolute;
        top: 68rpx;
        left: 80rpx;

        .name {
          font-size: 40rpx;
          font-weight: 500;
          color: #2d2b2a;
          line-height: 56rpx;
        }

        .brief-introduction {
          font-size: 28rpx;
          color: #666260;
          line-height: 40rpx;
        }
      }
    }

    //image {
    //	width: 100%;
    //	height: 100%;
    //}
  }
}

//button {
//	padding: 0;
//	line-height: 0;
//}
//
//button::after {
//	border: none;
//	background: transparent;
//}
</style>